<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Administrator
 * Date: 15/06/11
 * Time: 18:11
 * To change this template use File | Settings | File Templates.
 */
require_once('SQL.Result.class.php');
class SQL {


    private static $connection;
    private static $database;

    private static $executed_querys;

    public static function connect($host = '', $user = '', $pass = '', $database = '') {


        if (!empty($host) && !empty($user)) {
            self::connectdb($host, $user, $pass);

        }

       /* if (!is_null(Register::get('host')) && !is_null(Register::get('user'))) {
            self::connectdb(Register::get('host'), Register::get('user'), Register::get('password'));
        }  */
        if (!empty($database)) {
            self::select_database($database);
        }
        if (!empty($host) && !empty($user) && !empty($database)) {
            mysql_query("SET SESSION sql_mode = 'ANSI,ONLY_FULL_GROUP_BY'", self::$connection);
        }
    }

    public static function disconnect() {
        mysql_close(self::$connection);
    }


    private static function connectdb($host, $user, $pass = '') {
        self::$connection = mysql_connect($host, $user, $pass);
        if (!self::$connection) {
            trigger_error("SQL", E_USER_ERROR);

            //throw new Exception('could not connect to MYSQL Server');
        }
    }

    public static function select_database($database_name) {
        if (!empty($database_name)) {
            if (empty(self::$database)) {
                self::$database = $database_name;
            }
            if (!mysql_select_db($database_name, self::$connection)) {
                trigger_error("SQL", E_USER_ERROR);

                throw new Exception('Could not select database');
            }
        }
    }

    public static function execute($query) {
        if (!mysql_query($query, self::$connection)) {
            trigger_error("SQL", E_USER_ERROR);

          //  throw new Exception("could not execute the query");
        }
        self::$executed_querys++;
        return mysql_affected_rows(self::$connection);
    }

    public static function query($query) {
        if (!$result = mysql_query($query, self::$connection)) {
         //   trigger_error("SQL", E_USER_ERROR);

           throw new Exception("could not execute the query");
        }
        self::$executed_querys++;
        return new SQL_Result($result);
    }

    public static function getTotalQuerys() {
        return self::$executed_querys;
    }


    public static function getConnection() {
        return self::$connection;
    }

    public static function getDatabase() {
        return self::$database;
    }
}
